package dk.aau.walkietalkie.network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class TcpServerAsyncTask extends AsyncTask<Void, Void, String> {

	private String mTAG;
	private Context mContext;
	private int mPort;

	public TcpServerAsyncTask(Context context, final int port) {
		this.mContext = context;
		this.mPort = port;
		this.mTAG = mContext.getPackageName();
	}

	@Override
	protected String doInBackground(Void... params) {
		try {
			ServerSocket serverSocket = new ServerSocket(mPort);
			Log.d(mTAG, "Server: Socket opened");
			Socket client = serverSocket.accept();
			Log.d(mTAG, "Server: connection done");
			final File f = new File(Environment.getExternalStorageDirectory()
					+ "/" + mContext.getPackageName() + "/wifip2pshared-"
					+ System.currentTimeMillis() + ".txt");

			File dirs = new File(f.getParent());
			if (!dirs.exists())
				dirs.mkdirs();
			f.createNewFile();

			Log.d(mTAG, "server: copying files " + f.toString());
			InputStream inputstream = client.getInputStream();
			copyFile(inputstream, new FileOutputStream(f));
			serverSocket.close();
			return f.getAbsolutePath();
		} catch (IOException e) {
			Log.e(mTAG, e.getMessage());
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			Log.d(mTAG, "File copied - " + result);
			Intent intent = new Intent();
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse("file://" + result), "text/plain");
			// "image/*"
			mContext.startActivity(intent);
		}
	}

	@Override
	protected void onPreExecute() {
		Log.d(mTAG, "Opening a server socket");
	}

	public boolean copyFile(InputStream inputStream, OutputStream out) {
		byte buf[] = new byte[1024];
		int len;
		try {
			while ((len = inputStream.read(buf)) != -1) {
				out.write(buf, 0, len);

			}
			out.close();
			inputStream.close();
		} catch (IOException e) {
			Log.d(mTAG, e.toString());
			return false;
		}
		return true;
	}
  
}
